package com.amumu.drama.common.modules.order.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.amumu.drama.common.base.api.CommonPage;
import com.amumu.drama.common.commpont.RateLimiterCache;
import com.amumu.drama.common.commpont.idgenerator.IdGenerator;
import com.amumu.drama.common.config.redis.AppRateLimitType;
import com.amumu.drama.common.constant.*;
import com.amumu.drama.common.exception.ApiException;
import com.amumu.drama.common.exception.Asserts;
import com.amumu.drama.common.modules.category.mapping.GameVoMapping;
import com.amumu.drama.common.modules.coupon.dto.SmsCouponHistoryDetail;
import com.amumu.drama.common.modules.invitation.service.InvitationAnchorService;
import com.amumu.drama.common.modules.invitation.service.InvitationService;
import com.amumu.drama.common.modules.member.service.UmsMemberService;
import com.amumu.drama.common.modules.message.service.CancelOrderSender;
import com.amumu.drama.common.modules.order.cache.OrderSettingCache;
import com.amumu.drama.common.modules.order.dao.PortalOrderDao;
import com.amumu.drama.common.modules.order.dao.PortalOrderItemDao;
import com.amumu.drama.common.modules.order.dto.*;
import com.amumu.drama.common.modules.order.dto.req.OrderQuery;
import com.amumu.drama.common.modules.order.dto.req.PayOrderReq;
import com.amumu.drama.common.modules.order.dto.req.ValidateInvitationCodeReq;
import com.amumu.drama.common.modules.order.dto.resp.MemberOrderListResp;
import com.amumu.drama.common.modules.order.dto.resp.ValidateInvitationCodeResp;
import com.amumu.drama.common.modules.order.manager.OrderManager;
import com.amumu.drama.common.modules.order.mapper.OmsOrderItemRespMapping;
import com.amumu.drama.common.modules.order.mapper.OrderPayRespMapping;
import com.amumu.drama.common.modules.order.mapping.MemberOrderListRespMapping;
import com.amumu.drama.common.modules.order.service.*;
import com.amumu.drama.common.modules.service.RedisService;
import com.amumu.drama.common.modules.service.impl.payment.PaymentReq;
import com.amumu.drama.common.modules.service.impl.payment.PaymentResp;
import com.amumu.drama.common.utils.DateUtils;
import com.amumu.drama.common.utils.NumUtils;
import com.amumu.drama.common.utils.date.DatetimeUtils;
import com.amumu.drama.mapper.*;
import com.amumu.drama.model.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 前台订单管理Service
 * Created by macro on 2018/8/30.
 */
@Slf4j
@Service
public class OmsPortalOrderServiceImpl extends ServiceImpl<OmsOrderMapper, OmsOrder> implements OmsPortalOrderService {


    private static final Logger LOGGER = LoggerFactory.getLogger(OmsPortalOrderServiceImpl.class);
    @Autowired
    private OmsCartItemService cartItemService;
    @Autowired
    private UmsMemberReceiveAddressService memberReceiveAddressService;
    @Autowired
    private UmsMemberCouponService memberCouponService;
    @Autowired
    private UmsIntegrationConsumeSettingMapper integrationConsumeSettingMapper;
    @Autowired
    private PmsSkuStockMapper skuStockMapper;
    @Autowired
    private OmsOrderMapper omsOrderMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private PortalOrderItemDao orderItemDao;
    @Autowired
    private PmsProductCategoryMapper productCategoryMapper;
    @Autowired
    private SmsCouponHistoryMapper couponHistoryMapper;
    @Autowired
    private RedisService redisService;
    @Value("${redis.key.orderId}")
    private String REDIS_KEY_ORDER_ID;
    @Value("${redis.database}")
    private String REDIS_DATABASE;
    @Autowired
    private PortalOrderDao portalOrderDao;
    @Autowired
    private OmsOrderSettingMapper orderSettingMapper;
    @Autowired
    private OmsOrderItemMapper orderItemMapper;
    @Autowired
    private CancelOrderSender cancelOrderSender;
    @Autowired
    private InvitationService invitationService;
    @Autowired
    private PmsProductTemplateMapper productTemplateMapper;
    @Autowired
    private PaymentService paymentService;
    @Autowired
    private OmsPortalOrderService omsPortalOrderService;
    @Autowired
    private UmsMemberService umsMemberService;
    @Autowired
    private InvitationAnchorService invitationAnchorService;
    @Autowired
    private InvitationLogMapper invitationLogMapper;
    @Autowired
    private OrderManager orderManager;

    @Override
    public ValidateInvitationCodeResp validateInvitationCode(ValidateInvitationCodeReq request, UmsMember currentMember) {
        //判断是否是用户邀请码
        UmsMember member = null;
        try {
            Long memberId = Long.parseLong(request.getInvitationCode());
            //构建用户邀请信息
            member = umsMemberService.getById(memberId);
        } catch (NumberFormatException e) {
            log.error("验证邀请码：不是用户邀请码：invitationCode:{}", request.getInvitationCode(), e);
        }
        ValidateInvitationCodeResp resp = new ValidateInvitationCodeResp();
        resp.setInvitationCode(request.getInvitationCode());
        boolean firstOrder = queryFirstOrderStatus(currentMember);
        if (member != null) {
            if (!firstOrder) {
                throw new ApiException("非首次下单，不能使用邀请码");
            }
            resp.setInvitationType(InvitationTypeEnum.MEMBER.getCode());
            resp.setInviterMemberId(member.getId());
            resp.setInvitationDiscount(OrderSettingCache.INSTANCE.getValue(OmsOrderSetting::getInvitationDiscount));
        } else {
            //获取生效中的邀请码信息
            InvitationAnchor invitationAnchor = invitationAnchorService.getEffectiveInvitationAnchor(request.getInvitationCode());
            if (invitationAnchor == null) {
                throw new ApiException("邀请码无效");
            }
            if (Objects.equals(invitationAnchor.getNeedNewUser(), 1) && !firstOrder) {
                throw new ApiException("非首次下单，不能使用邀请码");
            }
            resp.setInvitationType(InvitationTypeEnum.ANCHOR.getCode());
            resp.setInvitationAnchor(invitationAnchor);
            resp.setInvitationDiscount(invitationAnchor.getDiscount());
        }
        return resp;
    }


    @Override
    public GenerateOrderResult generateOrder(OrderParam orderParam, UmsMember currentMember) {
        if (MapUtil.isEmpty(orderParam.getFeature())) {
            Asserts.fail("玩家信息为空");
        }
        if (orderParam.getProductSkuId() == null) {
            Asserts.fail("商品skuId为空");
        }
        PayTypeEnum payTypeEnum = PayTypeEnum.getByKey(orderParam.getPayType());
        if (payTypeEnum == null) {
            Asserts.fail("支付方式无效");
        }
        orderParam.setSourceType(orderParam.getSourceType() == null ? 0 : orderParam.getSourceType());
        if (SourceTypeEnum.getByCode(orderParam.getSourceType()) == null) {
            log.error("订单来源无效！");
            Asserts.fail("订单来源无效！");
        }
        //限流
        if (!RateLimiterCache.INSTANT.allowByKey("order", AppRateLimitType.ORDER)) {
            Asserts.fail("请求太过频繁,请稍候再试");
        }
        if (!umsMemberService.checkRealName(currentMember)) {
            Asserts.fail("下单前请进行实名认证～");
        }
        ValidateInvitationCodeResp validateInvitationCodeResp = null;
        if (StringUtils.isNotBlank(orderParam.getInvitationCode())) {
            ValidateInvitationCodeReq request = new ValidateInvitationCodeReq();
            request.setInvitationCode(orderParam.getInvitationCode());
            validateInvitationCodeResp = validateInvitationCode(request, currentMember);
            if (validateInvitationCodeResp == null) {
                Asserts.fail("邀请码无效");
            }
        }
        //获取sku库存
        PmsSkuStock skuStocks = skuStockMapper.selectById(orderParam.getProductSkuId());
        if (skuStocks == null) {
            LOGGER.error("用户:{}下单商品sku:{},商品不存在", currentMember.getId(), orderParam.getProductSkuId());
            Asserts.fail("商品sku不存在");
        }
        //获取游戏模板
        PmsProductTemplate productTemplate = productTemplateMapper.selectById(skuStocks.getProductTemplateId());
        if (productTemplate == null) {
            LOGGER.error("用户:{}下单商品sku:{},商品Id;{}商品不存在", currentMember.getId(), orderParam.getProductSkuId(), skuStocks.getProductId());
            Asserts.fail("商品不存在");
        }
        if (orderParam.getQuantity() == null) {
            LOGGER.warn("用户:{}下单商品sku:{},商品Id;{}数量为空，补充为1", currentMember.getId(), orderParam.getProductSkuId(), skuStocks.getProductId());
            orderParam.setQuantity(1);
        }
        if (skuStocks.getStock() <= 0 ||
                skuStocks.getStock() - skuStocks.getLockStock() < orderParam.getQuantity()) {
            LOGGER.error("库存不足，无法下单,productSkuCode={},stock:{},lockStock:{}", skuStocks.getSkuCode() + "_" + skuStocks.getId(), skuStocks.getStock(), skuStocks.getLockStock());
            Asserts.fail("库存不足，无法下单");
        }
        OmsOrderDetail order = omsPortalOrderService.insertOrder(orderParam, productTemplate, skuStocks, currentMember, validateInvitationCodeResp);
        GenerateOrderResult result = new GenerateOrderResult();
        result.setOrder(order);
        //订单创建成功，判断是否进行下一步支付
        if (Objects.equals(orderParam.getPaymentStatus(), 1)) {
            PaymentReq paymentReq = new PaymentReq();
            paymentReq.setOrderId(order.getId());
            paymentReq.setPayTypeEnum(payTypeEnum);
            paymentReq.setSourceTypeEnum(SourceTypeEnum.getByCode(orderParam.getSourceType()));
            paymentReq.setReturnUrl(orderParam.getReturnUrl());
            paymentReq.setOrderDetail(order);
            PaymentResp pay = paymentService.pay(currentMember, paymentReq);
            result.setOrderPayResp(OrderPayRespMapping.INSTANCE.convertTo(pay));
        }
        return result;
    }


    @Override
    public GenerateOrderResult payOrder(PayOrderReq request, UmsMember currentMember) {
        OmsOrderDetail order = omsPortalOrderService.detail(request.getOrderId());
        if (order == null) {
            Asserts.fail("订单不存在");
        }
        if (!Objects.equals(order.getMemberId(), currentMember.getId())) {
            Asserts.fail("订单不属于当前用户");
        }
        if (!(Objects.equals(PayStatusEnum.WAIT_PAY.getCode(), order.getPayStatus()) || Objects.equals(PayStatusEnum.PAYING.getCode(), order.getPayStatus()))) {
            Asserts.fail("订单状态不是待支付状态");
        }
        //判断订单是否已经过期无法支付
        Long normalOrderOverTime = OrderSettingCache.INSTANCE.getValue(OmsOrderSetting::getNormalOrderOvertime);
        LocalDateTime expireTime = order.getCreateTime().plusMinutes(normalOrderOverTime);
        if (LocalDateTime.now().isAfter(expireTime)) {
            Asserts.fail("订单超时关闭，请重新下单");
        }
        GenerateOrderResult resp = new GenerateOrderResult();
        PaymentReq paymentReq = new PaymentReq();
        paymentReq.setOrderId(order.getId());
        paymentReq.setOrderDetail(order);
        paymentReq.setPayTypeEnum(PayTypeEnum.getByKey(order.getPayType()));
        paymentReq.setSourceTypeEnum(SourceTypeEnum.getByCode(order.getSourceType()));
        paymentReq.setReturnUrl(request.getReturnUrl());
        PaymentResp paymentResp = paymentService.pay(currentMember, paymentReq);
        resp.setOrder(order);
        resp.setOrderPayResp(OrderPayRespMapping.INSTANCE.convertTo(paymentResp));
        return resp;
    }

    @Override
    public void cancelOrder(Long orderId, UmsMember currentMember) {
        OmsOrderDetail order = omsPortalOrderService.detail(orderId);
        if (order == null) {
            Asserts.fail("订单不存在");
        }
        if (!Objects.equals(order.getMemberId(), currentMember.getId())) {
            Asserts.fail("订单不属于当前用户");
        }
        if (!PayStatusEnum.WAIT_PAY_AND_PAYING_LIST.contains(PayStatusEnum.getByCode(order.getPayStatus()))) {
            Asserts.fail("订单不是待支付状态");
        }
        PaymentResp paymentResp = new PaymentResp();
        paymentResp.setPayStatusEnum(PayStatusEnum.FAIL);
        paymentResp.setPayRemark("用户取消订单");
        orderManager.updateOrderPayStatus(order.getId(), paymentResp, OperateTypeEnum.MEMBER, order.getMemberId());
    }


    @Override
    public ConfirmOrderResult generateConfirmOrder(List<Long> cartIds, UmsMember currentMember) {
        ConfirmOrderResult result = new ConfirmOrderResult();
        //获取购物车信息
        List<CartPromotionItem> cartPromotionItemList = cartItemService.listPromotion(currentMember.getId(), cartIds);
        result.setCartPromotionItemList(cartPromotionItemList);
        //获取用户收货地址列表
        List<UmsMemberReceiveAddress> memberReceiveAddressList = memberReceiveAddressService.list(currentMember);
        result.setMemberReceiveAddressList(memberReceiveAddressList);
        //获取用户可用优惠券列表
        List<SmsCouponHistoryDetail> couponHistoryDetailList = memberCouponService.listCart(cartPromotionItemList, 1, currentMember);
        result.setCouponHistoryDetailList(couponHistoryDetailList);
        //获取用户积分
        result.setMemberIntegration(currentMember.getIntegration());
        //获取积分使用规则
        UmsIntegrationConsumeSetting integrationConsumeSetting = integrationConsumeSettingMapper.selectByPrimaryKey(1L);
        result.setIntegrationConsumeSetting(integrationConsumeSetting);
        //计算总金额、活动优惠、应付金额
        ConfirmOrderResult.CalcAmount calcAmount = calcCartAmount(cartPromotionItemList);
        result.setCalcAmount(calcAmount);
        return result;
    }

    @Override
    public OmsOrderDetail insertOrder(OrderParam orderParam, PmsProductTemplate productTemplate, PmsSkuStock skuStocks, UmsMember currentMember, ValidateInvitationCodeResp invitationCodeResp) {
        //判断购物车中商品是否都有库存
        OmsOrderSetting orderSetting = OrderSettingCache.INSTANCE.getOrderSetting();
        if (Objects.isNull(orderSetting)) {
            Asserts.fail("系统异常，请稍后重试");
        }
        //生成下单商品信息
        List<OmsOrderItem> orderItemList = new ArrayList<>();
        OmsOrderItem orderCreateItem = new OmsOrderItem();
        orderCreateItem.setProductCategoryId(skuStocks.getProductCategoryId());
        orderCreateItem.setProductId(skuStocks.getId());
        orderCreateItem.setProductName(skuStocks.getSkuName());
        orderCreateItem.setProductPic(skuStocks.getPic());
        orderCreateItem.setProductSn(productTemplate.getDirectTemplateId());
        orderCreateItem.setProductPrice(skuStocks.getPrice());
        orderCreateItem.setProductCostPrice(skuStocks.getCostPrice());
        orderCreateItem.setProductQuantity(orderParam.getQuantity());
        orderCreateItem.setProductSkuId(skuStocks.getId());
        orderCreateItem.setProductSkuCode(skuStocks.getSkuCode());
        orderCreateItem.setFeature(JSONUtil.toJsonStr(orderParam.getFeature()));
        orderCreateItem.setProductAttr(skuStocks.getSpData());
        orderItemList.add(orderCreateItem);
        lockStock(orderItemList);

        //构建订单详情
        OmsOrderDetail order = new OmsOrderDetail();

        //转化为订单信息并插入数据库
        order.setMemberId(currentMember.getId());
        order.setCreateTime(LocalDateTime.now());
        order.setMemberUsername(currentMember.getUsername());
        // 插入玩家信息
        order.setFeature(JSONUtil.toJsonStr(orderParam.getFeature()));
        //计算订单总的应付金额
        order.setTotalAmount(calcTotalAmount(orderItemList));
        //设置邀请码 计算邀请优惠
        calcInvitationDiscountAmount(invitationCodeResp, order, currentMember);
        //支付方式：0->未支付；1->支付宝；2->微信
        order.setPayType(orderParam.getPayType());
        //设置支付供应商
        order.setPayProvider(PayProviderEnum.SUMA_PAY.getType());
        order.setDeliveryProvider(DeliveryProviderEnum.FULU.getCode());

        //设置使用的积分
        calcUseIntegration(order.getPayType(), order, currentMember, orderItemList);
        order.setPayAmount(calcPayAmount(order));
        //订单来源：0->未知；1->app订单 2-pc
        order.setSourceType(orderParam.getSourceType());


        //订单状态：0->待付款；1->待发货；2->已发货；3->已完成；4->已关闭；5->无效订单
        order.setStatus(OrderStatusEnum.WAIT_PAY.getCode());
        order.setPayStatus(PayStatusEnum.WAIT_PAY.getCode());
        order.setDeleteStatus(DeliveryStatusEnum.WAIT_DELIVERY.getCode());
        //订单类型：0->接口充值；1->人工订单 2->接口转人工 3->手动转接口
        order.setOrderType(0);

        //根据配置设置支付供应商
        if (PayTypeEnum.WX_PAY.getCode().equals(order.getPayType())) {
            order.setPayProvider(orderSetting.getWxPayProvider());
        } else if (PayTypeEnum.ALI_PAY.getCode().equals(order.getPayType())) {
            order.setPayProvider(orderSetting.getAliPayProvider());
        } else {
            order.setPayProvider(PayProviderEnum.WE_PLAYER.getType());
        }
        //根据配置设置发货供应商
        order.setDeliveryProvider(orderSetting.getDeliveryProvider());

        order.setAutoConfirmDay(orderSetting.getDeliveryDelayQueryOvertime());
        //订单类型：0->福禄订单；1->人工订单
        OrderTypeEnum orderTypeEnum = calcOrderType(orderSetting, skuStocks, order.getCreateTime());
        order.setOrderType(orderTypeEnum.getCode());
        if (OrderTypeEnum.MANUAL_DELIVERY.equals(orderTypeEnum)) {
            order.setDeliveryProvider(DeliveryProviderEnum.TAOBAO.getCode());
        }

        order.setReceiverPhone(currentMember.getPhone());
        order.setReceiverName(currentMember.getNickname());
        //0->未确认；1->已确认
        order.setConfirmStatus(0);
        order.setDeleteStatus(0);
        //插入order表和order_item表
        //生成订单号
        order.setOrderSn(generateOrderSn(order));
        orderMapper.insert(order);
        for (OmsOrderItem orderItem : orderItemList) {
            orderItem.setOrderId(order.getId());
            orderItem.setOrderSn(order.getOrderSn());
            orderItemDao.insert(orderItem);
        }
        if (invitationCodeResp != null) {
            InvitationLog invitationLog = new InvitationLog();
            invitationLog.setInviterMemberId(invitationCodeResp.getInviterMemberId());
            invitationLog.setInviteeMemberId(currentMember.getId());
            invitationLog.setType(invitationCodeResp.getInvitationType());
            invitationLog.setInvitationCode(invitationCodeResp.getInvitationCode());
            invitationLog.setDiscount(invitationCodeResp.getInvitationDiscount());
            invitationLog.setTotalAmount(order.getTotalAmount());
            invitationLog.setPayAmount(order.getPayAmount());
            invitationLog.setDiscountAmount(order.getInvitationDiscountAmount());
            invitationLog.setIntegrationStatus(IntegrationRewardStatusEnum.WAIT.getCode());
            invitationLog.setCreator(currentMember.getId() + "");
            InvitationAnchor invitationAnchor = invitationCodeResp.getInvitationAnchor();
            if (invitationAnchor != null) {
                invitationLog.setInvitationAnchorId(invitationAnchor.getId());
                invitationLog.setStartTime(invitationAnchor.getStartTime());
                invitationLog.setEndTime(invitationAnchor.getEndTime());
            }
            invitationLogMapper.insert(invitationLog);
        }
        order.setOrderItemList(orderItemList);
        return order;
    }

    //使用积分支付，设置积分支付优惠
    private void calcUseIntegration(Integer payType, OmsOrderDetail order, UmsMember currentMember, List<OmsOrderItem> orderItemList) {
        order.setIntegrationAmount(new BigDecimal("0"));
        if (Objects.equals(PayTypeEnum.WEIWAN_PAY.getCode(), payType)) {
            order.setUseIntegration(order.getTotalAmount());
            order.setIntegrationAmount(order.getTotalAmount());
            UmsMember member = umsMemberService.getById(currentMember.getId());
            BigDecimal integration = member.getIntegration();
            if (integration.compareTo(order.getUseIntegration()) < 0) {
                Asserts.fail("积分余额不足，无法进行支付～");
            }
        }
    }

    //设置邀请码 计算邀请优惠
    private void calcInvitationDiscountAmount(ValidateInvitationCodeResp invitationCodeResp, OmsOrderDetail order, UmsMember currentMember) {
        if (Objects.isNull(invitationCodeResp)) {
            order.setInvitationDiscountAmount(new BigDecimal("0"));
            return;
        }
        //判断邀请码类型
        order.setInvitationType(invitationCodeResp.getInvitationType());
        order.setInvitationCode(invitationCodeResp.getInvitationCode());
        order.setInvitationDiscountAmount(calcFirstOrderAmount(currentMember, order, invitationCodeResp));
    }

    /** 判断订单类型是否人工充值 */
    private OrderTypeEnum calcOrderType(OmsOrderSetting orderSettings, PmsSkuStock skuStocks, LocalDateTime createTime) {
        if (Objects.equals(skuStocks.getRechargeType(), OrderTypeEnum.MANUAL_DELIVERY)) {
            return OrderTypeEnum.MANUAL_DELIVERY;
        }
        if (Objects.equals(0, orderSettings.getManualOrderStatus())) {
            return OrderTypeEnum.MANUAL_DELIVERY;
        }
        if (StrUtil.isBlank(orderSettings.getManualOrderTime())) {
            return OrderTypeEnum.INTERFACE_DELIVERY;
        }
        String[] split = orderSettings.getManualOrderTime().split("~");
        if (split.length < 2) {
            return OrderTypeEnum.INTERFACE_DELIVERY;
        }
        if (DateUtils.timestampInTime(split[0], split[1], DatetimeUtils.toDateTime(createTime))
                && NumUtils.compareGe(skuStocks.getCostPrice(), orderSettings.getManualOrderAmount())) {
            return OrderTypeEnum.MANUAL_DELIVERY;
        }
        return OrderTypeEnum.INTERFACE_DELIVERY;
    }


    @Override
    public Integer paySuccess(Long orderId, Integer payType) {
        //修改订单支付状态
        OmsOrder order = new OmsOrder();
        order.setId(orderId);
        order.setStatus(1);
        order.setPaymentTime(LocalDateTime.now());
        order.setPayType(payType);
        omsOrderMapper.updateByPrimaryKeySelective(order);
        //恢复所有下单商品的锁定库存，扣减真实库存
        OmsOrderDetail orderDetail = portalOrderDao.getDetail(orderId);
        return portalOrderDao.updateSkuStock(orderDetail.getOrderItemList());
    }

    @Override
    public Integer paySuccessUpdate(Long orderId, Integer payType) {
        try {
            OmsOrder order = new OmsOrder();
            order.setId(orderId);
            order.setStatus(1);
            order.setPayStatus(1);
            order.setPayType(payType);
            order.setPaymentTime(LocalDateTime.now());
            omsOrderMapper.updateByPrimaryKeySelective(order);
            //恢复所有下单商品的锁定库存，扣减真实库存
            OmsOrderDetail orderDetail = portalOrderDao.getDetail(orderId);
            return portalOrderDao.updateSkuStock(orderDetail.getOrderItemList());
        } catch (Exception e) {
            LOGGER.error("{} paySuccessUpdate error", orderId, e);
            throw e;
        }
    }

    @Override
    public Integer cancelTimeOutOrder() {
        Integer count = 0;
        OmsOrderSetting orderSetting = orderSettingMapper.selectByPrimaryKey(1L);
        //查询超时、未支付的订单及订单详情
        List<OmsOrderDetail> timeOutOrders = portalOrderDao.getTimeOutOrders(orderSetting.getNormalOrderOvertime());
        if (CollectionUtils.isEmpty(timeOutOrders)) {
            return count;
        }
        //修改订单状态为交易取消
        List<Long> ids = new ArrayList<>();
        for (OmsOrderDetail timeOutOrder : timeOutOrders) {
            ids.add(timeOutOrder.getId());
        }
        portalOrderDao.updateOrderStatus(ids, 4);
        for (OmsOrderDetail timeOutOrder : timeOutOrders) {
            //解除订单商品库存锁定
            portalOrderDao.releaseSkuStockLock(timeOutOrder.getOrderItemList());
            //修改优惠券使用状态
            updateCouponStatus(timeOutOrder.getCouponId(), timeOutOrder.getMemberId(), 0);
            //返还使用积分
            if (timeOutOrder.getUseIntegration() != null) {
                UmsMember member = umsMemberService.getById(timeOutOrder.getMemberId());
                umsMemberService.updateIntegration(timeOutOrder.getMemberId(), member.getIntegration().add(timeOutOrder.getUseIntegration()));
            }
        }
        return timeOutOrders.size();
    }

    @Override
    public void sendDelayMessageCancelOrder(Long orderId) {
        //获取订单超时时间
        OmsOrderSetting orderSetting = orderSettingMapper.selectByPrimaryKey(1L);
        long delayTimes = orderSetting.getNormalOrderOvertime() * 60 * 1000;
        //发送延迟消息
        cancelOrderSender.sendMessage(orderId, delayTimes);
    }

    @Override
    public void confirmReceiveOrder(Long orderId, UmsMember member) {
        OmsOrder order = omsOrderMapper.selectByPrimaryKey(orderId);
        if (!member.getId().equals(order.getMemberId())) {
            Asserts.fail("不能确认他人订单！");
        }
        if (order.getStatus() != 2) {
            Asserts.fail("该订单还未发货！");
        }
        order.setStatus(3);
        order.setConfirmStatus(1);
        order.setReceiveTime(LocalDateTime.now());
        omsOrderMapper.updateByPrimaryKey(order);
    }

    public static Map<String, List<Integer>> ORDER_STATUS_MAP = Maps.newHashMap();

    static {
//        All->全部；WaitingPay->待付款；InProgress->进行中；Finished->已完成"
        ORDER_STATUS_MAP.put("All", Arrays.asList(
                OrderStatusEnum.WAIT_PAY.getCode(),
                OrderStatusEnum.WAIT_DELIVERY.getCode(),
                OrderStatusEnum.FINISHED.getCode(),
                OrderStatusEnum.REFUND.getCode(),
                OrderStatusEnum.CLOSED.getCode()));
        ORDER_STATUS_MAP.put("WaitingPay", Arrays.asList(
                OrderStatusEnum.WAIT_PAY.getCode()
        ));
        ORDER_STATUS_MAP.put("InProgress", Arrays.asList(
                OrderStatusEnum.WAIT_DELIVERY.getCode()
        ));
        ORDER_STATUS_MAP.put("Finished", Arrays.asList(
                OrderStatusEnum.FINISHED.getCode(),
                OrderStatusEnum.REFUND.getCode(),
                OrderStatusEnum.CLOSED.getCode()
        ));
    }

    @Override
    public CommonPage<OmsOrderDetail> list(String status, Integer pageNum, Integer pageSize, UmsMember member) {
        PageHelper.startPage(pageNum, pageSize);
        OmsOrderExample orderExample = new OmsOrderExample();
        OmsOrderExample.Criteria criteria = orderExample.createCriteria();
        criteria.andDeleteStatusEqualTo(0)
                .andMemberIdEqualTo(member.getId());
        if (status != null) {
            List<Integer> values = ORDER_STATUS_MAP.get(status);
            if (CollUtil.isEmpty(values)) {
                Asserts.fail("订单参数状态不合法");
            }
            criteria.andStatusIn(values);
        }
        orderExample.setOrderByClause("create_time desc");
        List<OmsOrder> orderList = omsOrderMapper.selectByExample(orderExample);
        CommonPage<OmsOrder> orderPage = CommonPage.restPage(orderList);
        //设置分页信息
        CommonPage<OmsOrderDetail> resultPage = new CommonPage<>();
        resultPage.setPageNum(orderPage.getPageNum());
        resultPage.setPageSize(orderPage.getPageSize());
        resultPage.setTotal(orderPage.getTotal());
        resultPage.setTotalPage(orderPage.getTotalPage());
        if (CollUtil.isEmpty(orderList)) {
            return resultPage;
        }
        //设置数据信息
        List<Long> orderIds = orderList.stream().map(OmsOrder::getId).collect(Collectors.toList());
        OmsOrderItemExample orderItemExample = new OmsOrderItemExample();
        orderItemExample.createCriteria().andOrderIdIn(orderIds);
        List<OmsOrderItem> orderItemList = orderItemMapper.selectByExample(orderItemExample);
        List<OmsOrderDetail> orderDetailList = new ArrayList<>();
        for (OmsOrder omsOrder : orderList) {
            OmsOrderDetail orderDetail = new OmsOrderDetail();
            BeanUtil.copyProperties(omsOrder, orderDetail);
            List<OmsOrderItem> relatedItemList = orderItemList.stream().filter(item -> item.getOrderId().equals(orderDetail.getId())).collect(Collectors.toList());
            orderDetail.setOrderItemList(relatedItemList);
            orderDetailList.add(orderDetail);
        }
        resultPage.setList(orderDetailList);
        return resultPage;
    }

    @Override
    public CommonPage<MemberOrderListResp> queryOrderList(OrderQuery request, UmsMember currentMember) {
        List<Integer> values = ORDER_STATUS_MAP.get(request.getStatus());
        if (CollUtil.isEmpty(values)) {
            Asserts.fail("订单参数状态不合法");
        }
        QueryWrapper<OmsOrder> queryWrapper = new QueryWrapper<OmsOrder>();
        queryWrapper.in("status", values);
        queryWrapper.eq("member_id", currentMember.getId());
        queryWrapper.eq("delete_status", 0);
        queryWrapper.orderByDesc("create_time");
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<OmsOrder> orderList = omsOrderMapper.selectList(queryWrapper);
        CommonPage<MemberOrderListResp> orderPage = CommonPage.restPageAndConvert(orderList, MemberOrderListRespMapping.INSTANCE::convertTo);
        //设置数据信息
        if (CollUtil.isNotEmpty(orderList)) {
            List<Long> orderIds = orderList.stream().map(OmsOrder::getId).collect(Collectors.toList());
            List<OmsOrderItem> orderItemList = orderItemMapper.selectList(new QueryWrapper<OmsOrderItem>().in("order_id", orderIds));
            Map<Long, List<OmsOrderItem>> itemMap = orderItemList.stream().collect(Collectors.groupingBy(OmsOrderItem::getOrderId));
            List<Long> productCategoryIds = orderItemList.stream().map(OmsOrderItem::getProductCategoryId).collect(Collectors.toList());
            Map<Long, List<PmsProductCategory>> productCategoryMap = productCategoryMapper.selectBatchIds(productCategoryIds).stream()
                    .collect(Collectors.groupingBy(PmsProductCategory::getId));
            for (MemberOrderListResp listResp : orderPage.getList()) {
                listResp.setOrderItemList(OmsOrderItemRespMapping.INSTANCE.convertTo(itemMap.get(listResp.getId())));
                if (CollUtil.isNotEmpty(listResp.getOrderItemList())) {
                    List<PmsProductCategory> productCategories = productCategoryMap.get(listResp.getOrderItemList().get(0).getProductCategoryId());
                    if (CollUtil.isNotEmpty(productCategories)) {
                        PmsProductCategory category = productCategories.get(0);
                        listResp.setGameVo(GameVoMapping.INSTANCE.convertTo(category));
                        PmsProductTemplate pmsProductTemplate = productTemplateMapper.selectByGameId(category.getId());
                        if (pmsProductTemplate != null) {
                            listResp.setCustomTemplateField(pmsProductTemplate.getCustomTemplateField());
                        }
                    }
                }
            }
        }
        return orderPage;
    }

    /**
     * 查询用户订单详情
     *
     * @param orderId
     */
    @Override
    public MemberOrderListResp orderDetail(Long orderId) {
        OmsOrder omsOrder = omsOrderMapper.selectById(orderId);
        MemberOrderListResp resp = MemberOrderListRespMapping.INSTANCE.convertTo(omsOrder);
        if (resp != null) {
            List<OmsOrderItem> orderItemList = orderItemMapper.selectList(new QueryWrapper<OmsOrderItem>().eq("order_id", resp.getId()));
            Map<Long, List<OmsOrderItem>> itemMap = orderItemList.stream().collect(Collectors.groupingBy(OmsOrderItem::getOrderId));
            List<Long> productCategoryIds = orderItemList.stream().map(OmsOrderItem::getProductCategoryId).collect(Collectors.toList());
            Map<Long, List<PmsProductCategory>> productCategoryMap = productCategoryMapper.selectBatchIds(productCategoryIds).stream()
                    .collect(Collectors.groupingBy(PmsProductCategory::getId));
            resp.setOrderItemList(OmsOrderItemRespMapping.INSTANCE.convertTo(itemMap.get(resp.getId())));
            if (CollUtil.isNotEmpty(resp.getOrderItemList())) {
                List<PmsProductCategory> productCategories = productCategoryMap.get(resp.getOrderItemList().get(0).getProductCategoryId());
                if (CollUtil.isNotEmpty(productCategories)) {
                    PmsProductCategory category = productCategories.get(0);
                    resp.setGameVo(GameVoMapping.INSTANCE.convertTo(category));
                    PmsProductTemplate pmsProductTemplate = productTemplateMapper.selectByGameId(category.getId());
                    if (pmsProductTemplate != null) {
                        resp.setCustomTemplateField(pmsProductTemplate.getCustomTemplateField());
                    }
                }
            }
        }
        return resp;
    }

    @Override
    public OmsOrderDetail detail(Long orderId) {
        OmsOrder omsOrder = omsOrderMapper.selectById(orderId);
        OmsOrderItemExample example = new OmsOrderItemExample();
        example.createCriteria().andOrderIdEqualTo(orderId);
        List<OmsOrderItem> orderItemList = orderItemMapper.selectByExample(example);
        OmsOrderDetail orderDetail = new OmsOrderDetail();
        BeanUtil.copyProperties(omsOrder, orderDetail);
        orderDetail.setOrderItemList(orderItemList);
        return orderDetail;
    }

    @Override
    public OmsOrder queryOrderByOrderId(Long orderId) {
        try {
            return omsOrderMapper.selectByPrimaryKey(orderId);
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public OmsOrder queryOrderByOrderSn(String orderSn) {
        try {
            return portalOrderDao.getDetailByOrderSn(orderSn);
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public void deleteOrder(Long orderId, UmsMember member) {
        OmsOrder order = omsOrderMapper.selectByPrimaryKey(orderId);
        if (!member.getId().equals(order.getMemberId())) {
            Asserts.fail("不能删除他人订单！");
        }
        if (order.getStatus() == 3 || order.getStatus() == 4) {
            order.setDeleteStatus(1);
            omsOrderMapper.updateByPrimaryKey(order);
        } else {
            Asserts.fail("只能删除已完成或已关闭的订单！");
        }
    }

    @Override
    public void paySuccessByOrderSn(String orderSn, Integer payType) {
        OmsOrderExample example = new OmsOrderExample();
        example.createCriteria()
                .andOrderSnEqualTo(orderSn)
                .andStatusEqualTo(0)
                .andDeleteStatusEqualTo(0);
        List<OmsOrder> orderList = omsOrderMapper.selectByExample(example);
        if (CollUtil.isNotEmpty(orderList)) {
            OmsOrder order = orderList.get(0);
            paySuccess(order.getId(), payType);
        }
    }

    @Override
    public boolean queryFirstOrderStatus(UmsMember currentMember) {
        return this.lambdaQuery().eq(OmsOrder::getMemberId, currentMember.getId())
                .eq(OmsOrder::getDeleteStatus, 0)
                .in(OmsOrder::getStatus, OrderStatusEnum.WAIT_PAY.getCode(), OrderStatusEnum.WAIT_DELIVERY.getCode(), OrderStatusEnum.FINISHED.getCode())
                .count() <= 0;
    }

    @Override
    public Long getCodeCount(Long invitationCodeId) {
        QueryWrapper<OmsOrder> entityQueryWrapper = new QueryWrapper<>();
        if (Objects.nonNull(invitationCodeId)) {
            entityQueryWrapper.eq("invitation_code_id", invitationCodeId);
        }
        entityQueryWrapper.in("status", Lists.newArrayList(0, 1, 2, 3));
        return orderMapper.selectCount(entityQueryWrapper);
    }

    /**
     * 生成18位订单编号:8位日期+2位平台号码+2位支付方式+6位以上自增id
     */
    private String generateOrderSn(OmsOrder order) {
//        StringBuilder sb = new StringBuilder();
//        String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
//        String key = REDIS_DATABASE + ":" + REDIS_KEY_ORDER_ID + date;
//        Long increment = redisService.incr(key, 1);
//        sb.append(String.format("%02d", order.getSourceType()));
//        sb.append(String.format("%02d", order.getPayType()));
//        String incrementStr = increment.toString();
//        if (incrementStr.length() <= 6) {
//            sb.append(String.format("%06d", increment));
//        } else {
//            sb.append(incrementStr);
//        }
        return IdGenerator.getOrderId(order.getMemberId()) + "";

    }

    /**
     * 删除下单商品的购物车信息
     */
    private void deleteCartItemList(List<CartPromotionItem> cartPromotionItemList, UmsMember currentMember) {
        List<Long> ids = new ArrayList<>();
        for (CartPromotionItem cartPromotionItem : cartPromotionItemList) {
            ids.add(cartPromotionItem.getId());
        }
        cartItemService.delete(currentMember.getId(), ids);
    }

    /**
     * 计算该订单赠送的成长值
     */
    private Integer calcGiftGrowth(List<OmsOrderItem> orderItemList) {
        Integer sum = 0;
        for (OmsOrderItem orderItem : orderItemList) {
            sum = sum + orderItem.getGiftGrowth() * orderItem.getProductQuantity();
        }
        return sum;
    }

    /**
     * 计算该订单赠送的积分
     */
    private BigDecimal calcGifIntegration(List<OmsOrderItem> orderItemList) {
        int sum = 0;
        for (OmsOrderItem orderItem : orderItemList) {
            sum += orderItem.getGiftIntegration() * orderItem.getProductQuantity();
        }
        return new BigDecimal(sum);
    }

    /**
     * 将优惠券信息更改为指定状态
     *
     * @param couponId  优惠券id
     * @param memberId  会员id
     * @param useStatus 0->未使用；1->已使用
     */
    private void updateCouponStatus(Long couponId, Long memberId, Integer useStatus) {
        if (couponId == null) {
            return;
        }
        //查询第一张优惠券
        SmsCouponHistoryExample example = new SmsCouponHistoryExample();
        example.createCriteria().andMemberIdEqualTo(memberId)
                .andCouponIdEqualTo(couponId).andUseStatusEqualTo(useStatus == 0 ? 1 : 0);
        List<SmsCouponHistory> couponHistoryList = couponHistoryMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(couponHistoryList)) {
            SmsCouponHistory couponHistory = couponHistoryList.get(0);
            couponHistory.setUseTime(new Date());
            couponHistory.setUseStatus(useStatus);
            couponHistoryMapper.updateByPrimaryKeySelective(couponHistory);
        }
    }

    private void handleRealAmount(List<OmsOrderItem> orderItemList) {
        for (OmsOrderItem orderItem : orderItemList) {
            //原价-促销优惠-优惠券抵扣-积分抵扣
            BigDecimal realAmount = orderItem.getProductPrice()
                    .subtract(orderItem.getPromotionAmount())
                    .subtract(orderItem.getCouponAmount())
                    .subtract(orderItem.getIntegrationAmount());
            orderItem.setRealAmount(realAmount);
        }
    }

    /**
     * 获取订单促销信息
     */
    private String getOrderPromotionInfo(List<OmsOrderItem> orderItemList) {
        StringBuilder sb = new StringBuilder();
        for (OmsOrderItem orderItem : orderItemList) {
            sb.append(orderItem.getPromotionName());
            sb.append(";");
        }
        String result = sb.toString();
        if (result.endsWith(";")) {
            result = result.substring(0, result.length() - 1);
        }
        return result;
    }

    /**
     * 计算订单应付金额
     */
    private BigDecimal calcPayAmount(OmsOrder order) {
        //总金额+运费-促销优惠-优惠券优惠-积分抵扣
        BigDecimal payAmount = order.getTotalAmount()
                .subtract(order.getIntegrationAmount())
                .subtract(order.getInvitationDiscountAmount());
        return payAmount;
    }

    /**
     * 计算订单需要使用的积分金额
     * 订单总金额-首单优惠金额
     */
    private BigDecimal calcIntegrationAmount(BigDecimal totalAmount, BigDecimal invitationDiscountAmount, Integer
            payType) {
        BigDecimal integrationAmount = new BigDecimal(0);
        if (!Objects.equals(PayTypeEnum.WEIWAN_PAY.getCode(), payType)) {
            return integrationAmount;
        }
        return totalAmount.subtract(invitationDiscountAmount);
    }

    /**
     * 计算订单优惠券金额
     */
    private BigDecimal calcCouponAmount(List<OmsOrderItem> orderItemList) {
        BigDecimal couponAmount = new BigDecimal(0);
        for (OmsOrderItem orderItem : orderItemList) {
            if (orderItem.getCouponAmount() != null) {
                couponAmount = couponAmount.add(orderItem.getCouponAmount().multiply(new BigDecimal(orderItem.getProductQuantity())));
            }
        }
        return couponAmount;
    }

    /**
     * 计算订单活动优惠
     */
    private BigDecimal calcPromotionAmount(List<OmsOrderItem> orderItemList) {
        BigDecimal promotionAmount = new BigDecimal(0);
        for (OmsOrderItem orderItem : orderItemList) {
            if (orderItem.getPromotionAmount() != null) {
                promotionAmount = promotionAmount.add(orderItem.getPromotionAmount().multiply(new BigDecimal(orderItem.getProductQuantity())));
            }
        }
        return promotionAmount;
    }

    /**
     * 计算首充优惠金额
     */
    private BigDecimal calcFirstOrderAmount(UmsMember currentMember, OmsOrderDetail
            order, ValidateInvitationCodeResp invitationCodeResp) {
        BigDecimal promotionAmount = new BigDecimal(0);
        //设置邀请人打折活动
        if (Objects.nonNull(invitationCodeResp)) {
            if (queryFirstOrderStatus(currentMember)) {
                order.setInvitationDiscount(invitationCodeResp.getInvitationDiscount());
                promotionAmount = order.getTotalAmount().multiply(new BigDecimal("1").subtract(invitationCodeResp.getInvitationDiscount()));
            }
        }
        return promotionAmount;
    }

    /**
     * 获取可用积分抵扣金额
     *
     * @param useIntegration 使用的积分数量
     * @param totalAmount    订单总金额
     * @param currentMember  使用的用户
     * @param hasCoupon      是否已经使用优惠券
     */
    private BigDecimal getUseIntegrationAmount(BigDecimal useIntegration, BigDecimal totalAmount, UmsMember
            currentMember, boolean hasCoupon) {
        BigDecimal zeroAmount = new BigDecimal(0);
        //判断用户是否有这么多积分
        if (useIntegration.compareTo(currentMember.getIntegration()) > 0) {
            return zeroAmount;
        }
        //根据积分使用规则判断是否可用
        //是否可与优惠券共用
        UmsIntegrationConsumeSetting integrationConsumeSetting = integrationConsumeSettingMapper.selectByPrimaryKey(1L);
        if (hasCoupon && integrationConsumeSetting.getCouponStatus().equals(0)) {
            //不可与优惠券共用
            return zeroAmount;
        }
        //是否达到最低使用积分门槛
        if (useIntegration.compareTo(integrationConsumeSetting.getUseUnit()) < 0) {
            return zeroAmount;
        }
        //是否超过订单抵用最高百分比
        BigDecimal integrationAmount = useIntegration.divide(integrationConsumeSetting.getUseUnit(), 2, RoundingMode.HALF_EVEN);
        BigDecimal maxPercent = new BigDecimal(integrationConsumeSetting.getMaxPercentPerOrder()).divide(new BigDecimal(100), 2, RoundingMode.HALF_EVEN);
        if (integrationAmount.compareTo(totalAmount.multiply(maxPercent)) > 0) {
            return zeroAmount;
        }
        return integrationAmount;
    }

    /**
     * 对优惠券优惠进行处理
     *
     * @param orderItemList       order_item列表
     * @param couponHistoryDetail 可用优惠券详情
     */
    private void handleCouponAmount(List<OmsOrderItem> orderItemList, SmsCouponHistoryDetail couponHistoryDetail) {
        SmsCoupon coupon = couponHistoryDetail.getCoupon();
        if (coupon.getUseType().equals(0)) {
            //全场通用
            calcPerCouponAmount(orderItemList, coupon);
        } else if (coupon.getUseType().equals(1)) {
            //指定分类
            List<OmsOrderItem> couponOrderItemList = getCouponOrderItemByRelation(couponHistoryDetail, orderItemList, 0);
            calcPerCouponAmount(couponOrderItemList, coupon);
        } else if (coupon.getUseType().equals(2)) {
            //指定商品
            List<OmsOrderItem> couponOrderItemList = getCouponOrderItemByRelation(couponHistoryDetail, orderItemList, 1);
            calcPerCouponAmount(couponOrderItemList, coupon);
        }
    }

    /**
     * 对每个下单商品进行优惠券金额分摊的计算
     *
     * @param orderItemList 可用优惠券的下单商品商品
     */
    private void calcPerCouponAmount(List<OmsOrderItem> orderItemList, SmsCoupon coupon) {
        BigDecimal totalAmount = calcTotalAmount(orderItemList);
        for (OmsOrderItem orderItem : orderItemList) {
            //(商品价格/可用商品总价)*优惠券面额
            BigDecimal couponAmount = orderItem.getProductPrice().divide(totalAmount, 3, RoundingMode.HALF_EVEN).multiply(coupon.getAmount());
            orderItem.setCouponAmount(couponAmount);
        }
    }

    /**
     * 获取与优惠券有关系的下单商品
     *
     * @param couponHistoryDetail 优惠券详情
     * @param orderItemList       下单商品
     * @param type                使用关系类型：0->相关分类；1->指定商品
     */
    private List<OmsOrderItem> getCouponOrderItemByRelation(SmsCouponHistoryDetail
                                                                    couponHistoryDetail, List<OmsOrderItem> orderItemList, int type) {
        List<OmsOrderItem> result = new ArrayList<>();
        if (type == 0) {
            List<Long> categoryIdList = new ArrayList<>();
            for (SmsCouponProductCategoryRelation productCategoryRelation : couponHistoryDetail.getCategoryRelationList()) {
                categoryIdList.add(productCategoryRelation.getProductCategoryId());
            }
            for (OmsOrderItem orderItem : orderItemList) {
                if (categoryIdList.contains(orderItem.getProductCategoryId())) {
                    result.add(orderItem);
                } else {
                    orderItem.setCouponAmount(new BigDecimal(0));
                }
            }
        } else if (type == 1) {
            List<Long> productIdList = new ArrayList<>();
            for (SmsCouponProductRelation productRelation : couponHistoryDetail.getProductRelationList()) {
                productIdList.add(productRelation.getProductId());
            }
            for (OmsOrderItem orderItem : orderItemList) {
                if (productIdList.contains(orderItem.getProductId())) {
                    result.add(orderItem);
                } else {
                    orderItem.setCouponAmount(new BigDecimal(0));
                }
            }
        }
        return result;
    }

    /**
     * 获取该用户可以使用的优惠券
     *
     * @param cartPromotionItemList 购物车优惠列表
     * @param couponId              使用优惠券id
     */
    private SmsCouponHistoryDetail getUseCoupon(List<CartPromotionItem> cartPromotionItemList, Long
            couponId, UmsMember currentMember) {
        List<SmsCouponHistoryDetail> couponHistoryDetailList = memberCouponService.listCart(cartPromotionItemList, 1, currentMember);
        for (SmsCouponHistoryDetail couponHistoryDetail : couponHistoryDetailList) {
            if (couponHistoryDetail.getCoupon().getId().equals(couponId)) {
                return couponHistoryDetail;
            }
        }
        return null;
    }

    /**
     * 计算总金额
     */
    private BigDecimal calcTotalAmount(List<OmsOrderItem> orderItemList) {
        BigDecimal totalAmount = new BigDecimal("0");
        for (OmsOrderItem item : orderItemList) {
            totalAmount = totalAmount.add(item.getProductPrice().multiply(new BigDecimal(item.getProductQuantity())));
        }
        return totalAmount;
    }

    /**
     * 锁定下单商品的所有库存
     */
    private void lockStockCartPromotionItem(List<CartPromotionItem> cartPromotionItemList) {
        for (CartPromotionItem cartPromotionItem : cartPromotionItemList) {
            PmsSkuStock skuStock = skuStockMapper.selectByPrimaryKey(cartPromotionItem.getProductSkuId());
            skuStock.setLockStock(skuStock.getLockStock() + cartPromotionItem.getQuantity());
            skuStockMapper.updateByPrimaryKeySelective(skuStock);
        }
    }

    /**
     * 锁定下单商品的所有库存
     */
    private void lockStock(List<OmsOrderItem> orderItemList) {
        for (OmsOrderItem orderItem : orderItemList) {
            PmsSkuStock skuStock = skuStockMapper.selectByPrimaryKey(orderItem.getProductSkuId());
            PmsSkuStock newSkuStock = new PmsSkuStock();
            newSkuStock.setId(skuStock.getId());
            newSkuStock.setLockStock(skuStock.getLockStock() + orderItem.getProductQuantity());
            skuStockMapper.updateByPrimaryKeySelective(newSkuStock);
        }
    }

    /**
     * 判断下单商品是否都有库存
     */
    private boolean hasStock(List<CartPromotionItem> cartPromotionItemList) {
        for (CartPromotionItem cartPromotionItem : cartPromotionItemList) {
            if (cartPromotionItem.getRealStock() == null //判断真实库存是否为空
                    || cartPromotionItem.getRealStock() <= 0 //判断真实库存是否小于0
                    || cartPromotionItem.getRealStock() < cartPromotionItem.getQuantity()) //判断真实库存是否小于下单的数量
            {
                return false;
            }
        }
        return true;
    }

    /**
     * 计算购物车中商品的价格
     */
    private ConfirmOrderResult.CalcAmount calcCartAmount(List<CartPromotionItem> cartPromotionItemList) {
        ConfirmOrderResult.CalcAmount calcAmount = new ConfirmOrderResult.CalcAmount();
        calcAmount.setFreightAmount(new BigDecimal(0));
        BigDecimal totalAmount = new BigDecimal("0");
        BigDecimal promotionAmount = new BigDecimal("0");
        for (CartPromotionItem cartPromotionItem : cartPromotionItemList) {
            totalAmount = totalAmount.add(cartPromotionItem.getPrice().multiply(new BigDecimal(cartPromotionItem.getQuantity())));
            promotionAmount = promotionAmount.add(cartPromotionItem.getReduceAmount().multiply(new BigDecimal(cartPromotionItem.getQuantity())));
        }
        calcAmount.setTotalAmount(totalAmount);
        calcAmount.setPromotionAmount(promotionAmount);
        calcAmount.setPayAmount(totalAmount.subtract(promotionAmount));
        return calcAmount;
    }


    public Map<String, Object> generateOrderOld(OrderParam orderParam, UmsMember currentMember) {
        List<OmsOrderItem> orderItemList = new ArrayList<>();
        if (MapUtil.isEmpty(orderParam.getFeature())) {
            Asserts.fail("玩家信息为空");
        }
        if (StringUtils.isBlank(orderParam.getInvitationCode()) && invitationService.validateCode(orderParam.getInvitationCode()) != null) {
            Asserts.fail("邀请码无效");
        }

        //获取购物车及优惠信息
//    todo   List<CartPromotionItem> cartPromotionItemList = cartItemService.listPromotion(currentMember.getId(), orderParam.getCartIds());
        List<CartPromotionItem> cartPromotionItemList = Lists.newArrayList();
        for (CartPromotionItem cartPromotionItem : cartPromotionItemList) {
            //生成下单商品信息
            OmsOrderItem orderItem = new OmsOrderItem();
            orderItem.setProductId(cartPromotionItem.getProductId());
            orderItem.setProductName(cartPromotionItem.getProductName());
            orderItem.setProductPic(cartPromotionItem.getProductPic());
            orderItem.setProductAttr(cartPromotionItem.getProductAttr());
            orderItem.setProductBrand(cartPromotionItem.getProductBrand());
            orderItem.setProductSn(cartPromotionItem.getProductSn());
            orderItem.setProductPrice(cartPromotionItem.getPrice());
            orderItem.setProductQuantity(cartPromotionItem.getQuantity());
            orderItem.setProductSkuId(cartPromotionItem.getProductSkuId());
            orderItem.setProductSkuCode(cartPromotionItem.getProductSkuCode());
            orderItem.setProductCategoryId(cartPromotionItem.getProductCategoryId());
            orderItem.setPromotionAmount(cartPromotionItem.getReduceAmount());
            orderItem.setPromotionName(cartPromotionItem.getPromotionMessage());
            orderItem.setGiftIntegration(cartPromotionItem.getIntegration());
            orderItem.setGiftGrowth(cartPromotionItem.getGrowth());
            orderItem.setFeature(JSONUtil.toJsonStr(orderParam.getFeature()));
            orderItemList.add(orderItem);
        }
        //判断购物车中商品是否都有库存
//        if (!hasStock(cartPromotionItemList)) {
//            Asserts.fail("库存不足，无法下单");
//        }
//        //判断使用使用了优惠券
//        if (orderParam.getCouponId() == null) {
//            //不用优惠券
//            for (OmsOrderItem orderItem : orderItemList) {
//                orderItem.setCouponAmount(new BigDecimal(0));
//            }
//        } else {
//            //使用优惠券
//            SmsCouponHistoryDetail couponHistoryDetail = getUseCoupon(cartPromotionItemList, orderParam.getCouponId());
//            if (couponHistoryDetail == null) {
//                Asserts.fail("该优惠券不可用");
//            }
//            //对下单商品的优惠券进行处理
//            handleCouponAmount(orderItemList, couponHistoryDetail);
//        }
        //判断是否使用积分
//        if (orderParam.getUseIntegration() == null || orderParam.getUseIntegration().equals(0)) {
        //不使用积分
        for (OmsOrderItem orderItem : orderItemList) {
            orderItem.setIntegrationAmount(new BigDecimal(0));
        }
//        } else {
//            //使用积分
//            BigDecimal totalAmount = calcTotalAmount(orderItemList);
////      todd      boolean hasCoupon = orderParam.getCouponId() != null;
//            boolean hasCoupon = true;
//            BigDecimal integrationAmount = getUseIntegrationAmount(orderParam.getUseIntegration(), totalAmount, currentMember, hasCoupon);
//            if (integrationAmount.compareTo(new BigDecimal(0)) == 0) {
//                Asserts.fail("积分不可用");
//            } else {
//                //可用情况下分摊到可用商品中
//                for (OmsOrderItem orderItem : orderItemList) {
//                    BigDecimal perAmount = orderItem.getProductPrice().divide(totalAmount, 3, RoundingMode.HALF_EVEN).multiply(integrationAmount);
//                    orderItem.setIntegrationAmount(perAmount);
//                }
//            }
//        }
        //计算order_item的实付金额
        handleRealAmount(orderItemList);
        //进行库存锁定
        this.lockStockCartPromotionItem(cartPromotionItemList);
        //根据商品合计、运费、活动优惠、优惠券、积分计算应付金额
        OmsOrder order = new OmsOrder();
        order.setDiscountAmount(new BigDecimal(0));
        order.setTotalAmount(calcTotalAmount(orderItemList));
        order.setFreightAmount(new BigDecimal(0));
        order.setPromotionAmount(calcPromotionAmount(orderItemList));
        order.setPromotionInfo(getOrderPromotionInfo(orderItemList));
//   todo     Long couponId = orderParam.getCouponId();
        Long couponId = 0L;
        if (couponId == null) {
            order.setCouponAmount(new BigDecimal(0));
        } else {
            order.setCouponId(couponId);
            order.setCouponAmount(calcCouponAmount(orderItemList));
        }
//        if (orderParam.getUseIntegration() == null) {
        order.setIntegration(new BigDecimal(0));
        order.setIntegrationAmount(new BigDecimal(0));
//        } else {
//            order.setIntegration(orderParam.getUseIntegration());
//            order.setIntegrationAmount(calcIntegrationAmount(orderItemList, order.getPayType()));
//        }
        // 插入玩家信息
        order.setFeature(JSONUtil.toJsonStr(orderParam.getFeature()));
        order.setPayAmount(calcPayAmount(order));
        //转化为订单信息并插入数据库
        order.setMemberId(currentMember.getId());
        order.setCreateTime(LocalDateTime.now());
        order.setMemberUsername(currentMember.getUsername());
        //支付方式：0->未支付；1->支付宝；2->微信
        order.setPayType(orderParam.getPayType());
        //订单来源：0->PC订单；1->app订单
        order.setSourceType(1);
        //订单状态：0->待付款；1->待发货；2->已发货；3->已完成；4->已关闭；5->无效订单
        order.setStatus(0);
        //订单类型：0->正常订单；1->秒杀订单
        order.setOrderType(0);
        //收货人信息：姓名、电话、邮编、地址
//        todo Long memberReceiveAddressId = orderParam.getMemberReceiveAddressId();
        Long memberReceiveAddressId = 0L;
        UmsMemberReceiveAddress address = memberReceiveAddressService.getItem(memberReceiveAddressId, currentMember);
        order.setReceiverName(address.getName());
        order.setReceiverPhone(address.getPhoneNumber());
        order.setReceiverPostCode(address.getPostCode());
        order.setReceiverProvince(address.getProvince());
        order.setReceiverCity(address.getCity());
        order.setReceiverRegion(address.getRegion());
        order.setReceiverDetailAddress(address.getDetailAddress());
        //0->未确认；1->已确认
        order.setConfirmStatus(0);
        order.setDeleteStatus(0);
        //计算赠送积分
        order.setIntegration(calcGifIntegration(orderItemList));
        //计算赠送成长值
        order.setGrowth(calcGiftGrowth(orderItemList));
        //生成订单号
        order.setOrderSn(generateOrderSn(order));
        //设置自动收货天数
        List<OmsOrderSetting> orderSettings = orderSettingMapper.selectByExample(new OmsOrderSettingExample());
        if (CollUtil.isNotEmpty(orderSettings)) {
            order.setAutoConfirmDay(orderSettings.get(0).getDeliveryDelayQueryOvertime());
        }
        //插入order表和order_item表
        omsOrderMapper.insert(order);
        for (OmsOrderItem orderItem : orderItemList) {
            orderItem.setOrderId(order.getId());
            orderItem.setOrderSn(order.getOrderSn());
            orderItemDao.insert(orderItem);
        }
        //如使用优惠券更新优惠券使用状态
        if (couponId != null) {
            updateCouponStatus(couponId, currentMember.getId(), 1);
        }
        //如使用积分需要扣除积分
//        if (orderParam.getUseIntegration() != null) {
//            order.setUseIntegration(orderParam.getUseIntegration());
//            if (currentMember.getIntegration() == null) {
//                currentMember.setIntegration(new BigDecimal(0));
//            }
//            memberService.updateIntegration(currentMember.getId(), currentMember.getIntegration().subtract(orderParam.getUseIntegration()));
//            UmsIntegrationChangeHistory integrationChangeHistory = new UmsIntegrationChangeHistory();
//            integrationChangeHistory.setMemberId(currentMember.getId());
//            integrationChangeHistory.setChangeCount(orderParam.getUseIntegration());
//            integrationChangeHistory.setOperateMan(currentMember.getUsername());
//            integrationChangeHistory.setChangeType(1);
//            integrationChangeHistory.setOperateNote("订单支付抵扣");
//            bonusPointService.createBonusPointRecord(integrationChangeHistory);
//        }
        //删除购物车中的下单商品
//        deleteCartItemList(cartPromotionItemList, currentMember);
        //发送延迟消息取消订单
        sendDelayMessageCancelOrder(order.getId());
        Map<String, Object> result = new HashMap<>();
        result.put("order", order);
        result.put("orderItemList", orderItemList);
        return result;
    }
}
